package com.atguigu.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.product.dao.SkuInfoDao;
import com.atguigu.product.entity.SkuImagesEntity;
import com.atguigu.product.entity.SkuInfoEntity;
import com.atguigu.product.entity.SpuInfoDescEntity;
import com.atguigu.product.feign.SeckillFeignService;
import com.atguigu.product.service.*;
import com.atguigu.product.vo.SeckillSkuVo;
import com.atguigu.product.vo.SkuItemSaleAttrVo;
import com.atguigu.product.vo.SpuItemAttrGroupVo;
import com.atguigu.product.vo.SkuItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;


    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Autowired
    private ThreadPoolExecutor executor;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * Sku检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        LambdaQueryWrapper<SkuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();

        //检索条件-> 分类id
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !("0".equalsIgnoreCase(catelogId)) ) {
            queryWrapper.eq(SkuInfoEntity::getCatalogId, catelogId);
        }
        //检索条件-> 品牌id
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !("0".equalsIgnoreCase(brandId))) {
            queryWrapper.eq(SkuInfoEntity::getBrandId, brandId);
        }

        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min)) {
            queryWrapper.ge(SkuInfoEntity::getPrice, min);
        }


        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(BigDecimal.ZERO)==1) {
                    queryWrapper.le(SkuInfoEntity::getPrice, max);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(k->{
                k.like(SkuInfoEntity::getSkuName, key)
                .or()
                .eq(SkuInfoEntity::getSkuId, key)
                ;
            });
        }


        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {

        List<SkuInfoEntity> list = this.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId, spuId));
        return list;
    }

    /**
     * 获取skiu商品详情
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVo skuItemVo = new SkuItemVo();

        //因为第一个任务的返回值后面要用所以用supplyAsync()
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1. sku的基本信息   pms_sku_info
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo.setSkuInfo(skuInfo);
            return skuInfo;
        }, executor);

        //因为除了第二步不依赖第一步的结果外，其他全部任务依赖第一步的返回结果，
        // 所以其他的任务是并行的，第一步的任务是最先执行的
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3. spu下的sku组合，即销售属性
            List<SkuItemSaleAttrVo> saleAttrVos = saleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setAttrValues(saleAttrVos);
        }, executor);


        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4. spu的介绍, pms    pms_spu_info_desc
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfoDesc);
        }, executor);


        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5. spu的规格参数
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getGroupWithAttrBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);


        //第二步并不依赖于第一步，所以另开一个任务执行异步即可
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2. sku的图片信息   pms_spu_images
            List<SkuImagesEntity> imagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setIamges(imagesEntities);
        }, executor);

        //查询当前sku是否参与当前秒杀优惠
        CompletableFuture<Void> sekillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillSkuVo seckillInfoVo = r.getData(new TypeReference<SeckillSkuVo>() {
                });
                long current = System.currentTimeMillis();
                //如果返回结果不为空并且活动未过期，设置秒杀信息
                if (seckillInfoVo!=null && current<seckillInfoVo.getEndTime()) {
                    skuItemVo.setSeckillSkuVo(seckillInfoVo);
                }
            }
        }, executor);


        //等到所有任务执行完成
        //这里的get()起阻塞作用， 不然主进程不会等待
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture, sekillFuture).get();

        return skuItemVo;
    }

}